/*
 * These files are distributed under the terms of the GNU GPLv2, the GNU General
 * Public version 2. See LICENSE.txt
 */
package fileCommodore.model;

import java.util.*;

import org.apache.commons.vfs.*;

import fileCommodore.*;

/**
 * @author nado18@gmail.com, on Jul 14, 2007
 */
public class FileObjectTableModel extends MyTableModel<FileRowItem>
	implements
		FileListener
{
	private SingleDirectoryMonitor sdm = new SingleDirectoryMonitor( this );
	private FileObject current;
	private Vector<PathChangeListener> listeners =
			new Vector<PathChangeListener>();
	
	public FileObjectTableModel()
	{
		super( "Icon", "Name", "Size" );
	}
	
	public void addPathChangeListener( PathChangeListener pcl )
	{
		listeners.add( pcl );
	}
	
	public void removePathChangeListener( PathChangeListener pcl )
	{
		listeners.remove( pcl );
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getValueAt(int, int)
	 */
	public Object getValueAt( int rowIndex, int columnIndex )
	{
		if (isValidCell( rowIndex, columnIndex ))
		{
			FileRowItem fri = getItemAt( rowIndex );
			switch (columnIndex)
			{
				case 0:
					return fri.getIcon();
				case 1:
					return fri;
				case 2:
					return fri.getSize();
			}
		}
		
		return null;
	}
	
	public FileObject getCurrent()
	{
		return current;
	}
	
	public void changeTo( FileObject o ) throws FileSystemException
	{
		if (null != o)
		{
			if (null != current)
			{
				sdm.removeFile( current );
			}
			current = o;
			try
			{
				sdm.addFile( current );
			}
			catch (Exception ex)
			{
				// TODO: What's wrong with this?!
				ex.printStackTrace();
			}
			
			boolean showHidden = Config.showHiddenFiles();
			
			Vector<FileRowItem> items = new Vector<FileRowItem>();
			for (FileObject file : o.getChildren())
			{
				FileRowItem fileRowItem = new FileRowItem( file );
				if (showHidden || fileRowItem.isVisible())
				{
					items.add( fileRowItem );
				}
			}
			
			setItems( items );
			
			for (PathChangeListener pcl : listeners)
			{
				pcl.pathChanged();
			}
			
		}
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.commons.vfs.FileListener#fileChanged(org.apache.commons.vfs.FileChangeEvent)
	 */
	public void fileChanged( FileChangeEvent arg0 ) throws Exception
	{
		reload();
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.commons.vfs.FileListener#fileCreated(org.apache.commons.vfs.FileChangeEvent)
	 */
	public void fileCreated( FileChangeEvent arg0 ) throws Exception
	{
		reload();
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.commons.vfs.FileListener#fileDeleted(org.apache.commons.vfs.FileChangeEvent)
	 */
	public void fileDeleted( FileChangeEvent arg0 ) throws Exception
	{
		reload();
	}
	
	private void reload()
	{
		try
		{
			changeTo( current );
		}
		catch (FileSystemException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
